import React, { useState, useMemo, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Input, List, Avatar, Badge, Tabs, Space, Typography, Empty } from 'antd';
import { SearchOutlined, UserOutlined, MessageOutlined, RobotOutlined, CommentOutlined } from '@ant-design/icons';
import styles from './message.module.css';
import { getAllMessages, getUserData } from './messageStore';

const { Text } = Typography;

export default function Message() {
  const navigate = useNavigate();
  const [activeTab, setActiveTab] = useState('all');
  const [searchText, setSearchText] = useState('');
  const [chatList, setChatList] = useState([
    {
      id: 1,
      name: '用户_qI5',
      avatar: <UserOutlined style={{ fontSize: 24 }} />,
      lastMessage: '你好',
      time: '10:30',
      unread: 0,
      type: 'chat'
    },
    {
      id: 2,
      name: 'DeepSeek AI 助手',
      avatar: <RobotOutlined style={{ fontSize: 24 }} />,
      lastMessage: '我可以帮你解答任何问题...',
      time: '昨天',
      unread: 0,
      type: 'ai'
    },
    {
      id: 3,
      name: '群聊：前端开发',
      avatar: <MessageOutlined style={{ fontSize: 24 }} />,
      lastMessage: '张三: React 18有哪些新特性？',
      time: '昨天',
      unread: 5,
      type: 'chat'
    },
    {
      id: 4,
      name: '李四',
      avatar: <UserOutlined style={{ fontSize: 24 }} />,
      lastMessage: '项目进度如何了？',
      time: '周一',
      unread: 0,
      type: 'chat'
    },
    {
      id: 5,
      name: '好友聊天',
      avatar: <UserOutlined style={{ fontSize: 24 }} />,
      lastMessage: '下午有时间一起吃饭吗？',
      time: '周日',
      unread: 2,
      type: 'chat'
    }
  ]);
  
  // 从messageStore获取消息并更新聊天列表
  useEffect(() => {
    // 获取用户数据
    const userData = getUserData();
    // 获取所有聊天消息
    const messages = getAllMessages();
    
    // 如果有聊天消息和用户数据，更新好友聊天的最新消息
    if (messages.length > 0 && userData) {
      // 获取最新的消息
      const latestMessage = messages[messages.length - 1];
      
      // 更新聊天列表，将最新消息添加到好友聊天中
      setChatList(prevList => {
        // 创建新的聊天列表
        const newList = [...prevList];
        
        // 查找好友聊天项
        const chatIndex = newList.findIndex(item => item.id === 1 && item.type === 'chat');
        
        if (chatIndex !== -1) {
          // 更新现有的好友聊天项
          newList[chatIndex] = {
            ...newList[chatIndex],
            name: latestMessage.isMe ? '好友聊天' : latestMessage.user, // 显示对方的名字
            lastMessage: latestMessage.text,
            time: latestMessage.time,
            unread: newList[chatIndex].unread + (latestMessage.isMe ? 0 : 1)
          };
        } else {
          // 如果不存在，添加新的好友聊天项
          newList.unshift({
            id: 1,
            name: latestMessage.isMe ? '好友聊天' : latestMessage.user, // 显示对方的名字
            avatar: <UserOutlined style={{ fontSize: 24 }} />,
            lastMessage: latestMessage.text,
            time: latestMessage.time,
            unread: 0,
            type: 'chat'
          });
        }
        
        return newList;
      });
    }
    
    // 添加事件监听器，监听localStorage变化
    const handleStorageChange = (e) => {
      if (e.key === 'chat_messages_v3') {
        // 当消息存储发生变化时，重新获取消息并更新聊天列表
        const updatedMessages = getAllMessages();
        if (updatedMessages.length > 0) {
          const latestMsg = updatedMessages[updatedMessages.length - 1];
          
          setChatList(prevList => {
            const newList = [...prevList];
            const chatIndex = newList.findIndex(item => item.id === 1 && item.type === 'chat');
            
            if (chatIndex !== -1) {
              newList[chatIndex] = {
                ...newList[chatIndex],
                name: latestMsg.isMe ? '好友聊天' : latestMsg.user, // 显示对方的名字
                lastMessage: latestMsg.text,
                time: latestMsg.time,
                unread: newList[chatIndex].unread + (latestMsg.isMe ? 0 : 1)
              };
            }
            
            return newList;
          });
        }
      }
    };
    
    window.addEventListener('storage', handleStorageChange);
    
    // 组件卸载时移除事件监听器
    return () => {
      window.removeEventListener('storage', handleStorageChange);
    };
  }, []);

  const filteredChatList = useMemo(() => {
    // First filter by active tab
    let result = activeTab === 'all'
      ? [...chatList]
      : chatList.filter(chat => chat.type === activeTab);

    // Then filter by search text if it exists
    if (searchText.trim()) {
      const searchTerm = searchText.toLowerCase();
      result = result.filter(chat =>
        chat.name.toLowerCase().includes(searchTerm) ||
        chat.lastMessage.toLowerCase().includes(searchTerm)
      );
    }

    return result;
  }, [activeTab, searchText, chatList]);

  const handleChatItemClick = (item) => {
    if (item.type === 'ai') {
      navigate('/deepAI');
    } else {
      navigate('/chat');
    }
  };

  const handleSearchChange = (e) => {
    setSearchText(e.target.value);
  };

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <h2>消息</h2>
      </div>

      <div className={styles.search}>
        <Input
          placeholder="搜索朋友"
          prefix={<SearchOutlined />}
          allowClear
          value={searchText}
          onChange={handleSearchChange}
        />
      </div>

      <Tabs
        activeKey={activeTab}
        onChange={setActiveTab}
        centered
        items={[
          { key: 'all', label: '全部' },
          { key: 'chat', label: '聊天' },
          { key: 'ai', label: 'AI助手' }
        ]}
      />

      <List
        className={styles.list}
        itemLayout="horizontal"
        dataSource={filteredChatList}
        renderItem={(item) => (
          <List.Item
            className={styles.listItem}
            onClick={() => handleChatItemClick(item)}
          >
            <List.Item.Meta
              avatar={
                <Badge count={item.unread} size="small" className={styles.badgeCount}>
                  <Avatar icon={item.avatar} className={styles.customAvatar} />
                </Badge>
              }
              title={<Text strong>{item.name}</Text>}
              description={
                <div className={styles.preview}>
                  <Text ellipsis style={{ maxWidth: '70%' }}>{item.lastMessage}</Text>
                </div>
              }
            />
            <div className={styles.time}>{item.time}</div>
          </List.Item>
        )}
        locale={{
          emptyText: (
            <div className={styles.emptyState}>
              <CommentOutlined className={styles.emptyIcon} />
              <p>暂无消息</p>
            </div>
          )
        }}
      />
    </div>
  );
}
